﻿using fuzhu;
using LH.Models.APAR;
using Microsoft.Extensions.Logging;
using NetTaste;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.AS;
using XXX.Models.GL;
using XXX.Models.U8Entity;
using XXX.Models.WDFT;
using ZDEntity;

namespace Yonyou.U8.BO
{
    //取glmodel，为来源参照
    public class WDFTInventoryVM : WDFT_InventoryQuery
    {   
            

           
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public static string cDatabase = "";



        /// <summary>
        /// 产品查询;名称+材质+厚度+形状(规格型号)+直径+直边高度
        /// </summary>
        /// <returns></returns>
        public RetModel2 CPQuery()
        {
            try
            {

                //读取材质
                string cCaiZhi = SqlsugarHelper.Instance.Queryable<WDFT_CaiZhi>().Where(x => x.CNo == cInvName)
                    .Select(x => x.CCardName)
                    .First();
                if (string.IsNullOrWhiteSpace(cCaiZhi))
                {
                    return DBService.ReErrObject("U8中没有建立此材质对照:"+ cInvName);
                }
                cCaiZhi = cCaiZhi + "封头";
                // 查询所有
                var exp = Expressionable.Create<Inventory, InventoryClass>() // 创建表达式
                    .AndIF(!string.IsNullOrWhiteSpace(cInvName), (x,  z) => x.cInvName==cCaiZhi) // 按名称筛选
                    .AndIF(!string.IsNullOrWhiteSpace(cInvCName), (x, z) => z.cInvCName.Contains(cInvCName)) // 按分类名称筛选
                    .AndIF(!string.IsNullOrWhiteSpace(cInvStd), (x,  z) => x.cInvStd.Contains(cInvStd)) // 按标准筛选
                    .And((x,  z) => x.cInvCCode.Substring(0, 2) == "06" || x.cInvCCode.Substring(0, 2) == "07"); // 按分类代码筛选

                // 按厚度筛选
                if (thickness.HasValue)
                {
                    int formattedThickness =(int)(Math.Round(thickness.Value, 1)*10);
                    string cthick = "0000" + (formattedThickness).ToString();
                    string resultthick = cthick.Substring(cthick.Length - 4);
                    exp.And((x,  z) =>
                        !string.IsNullOrWhiteSpace(x.cInvCode) &&
                        x.cInvCode.Length >= 16 &&
                        x.cInvCode.Substring(6, 4) == resultthick);

                  
                }

                // 按直径筛选
                if (diameter.HasValue)
                {
                    int formattedDiameter =(int)( Math.Round(diameter.Value, 1)*10);
                    string cdiameter = "000000" + (formattedDiameter ).ToString();
                    string resultdiameter = cdiameter.Substring(cdiameter.Length - 6);
                    exp.And((x, z) =>
                        !string.IsNullOrWhiteSpace(x.cInvCode) &&
                        x.cInvCode.Length >= 18 &&
                        x.cInvCode.Substring(10, 6) == resultdiameter);
                }
                if (!string.IsNullOrWhiteSpace(shape))
                {

                    //读取形状的编码
                    string cNo = SqlsugarHelper.Instance.Queryable<WDFT_XingZhuang>().Where(x=>x.CCardName==shape)
                        .Select(x => x.CNo)
                        .First();
                    if (string.IsNullOrWhiteSpace(cNo))
                    {
                        return DBService.ReErrObject("查询不到对应的形状编码");
                    }
                    // 按形状筛选
                    exp.And((x, z) =>
                        !string.IsNullOrWhiteSpace(x.cInvCode) &&
                        x.cInvCode.Length >= 16 &&
                        x.cInvCode.Substring(16, 2) == cNo);
                }
               

                // 生成表达式
                var whereExpression = exp.ToExpression(); // 直接调用 ToExpression()，

                var list1 = SqlsugarHelper.Instance.Queryable<Inventory>() // 主表用当前db就行了
                    .LeftJoin<InventoryClass>((x,  z) => x.cInvCCode == z.cInvCCode)
                    .Where(whereExpression)
                    .Select((x,  z) => new WDFT_InventoryQuery_Res()
                    {
                        cInvCode = x.cInvCode,
                        cInvName = x.cInvName,
                        cInvStd = x.cInvStd,
                        cInvCCode = x.cInvCCode,
                        cInvCName = z.cInvCName,
                    }).ToList();

                if (list1.Count > 0)
                {
                    return DBService.ReOKObject(list1);
                }
                else
                {
                    return DBService.ReErrObject("查询不到列表");
                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }


        /// <summary>
        /// 材料查询
        /// </summary>
        /// <returns></returns>
        public RetModel2 CLQuery()
        {
            try
            {
                // 查询所有
                var exp = Expressionable.Create<Inventory,  InventoryClass>() // 创建表达式
                    .AndIF(!string.IsNullOrWhiteSpace(cInvName), (x,  z) => x.cInvName.Contains(cInvName)) // 按名称筛选
                    .AndIF(!string.IsNullOrWhiteSpace(cInvCName), (x, z) => z.cInvCName.Contains(cInvCName)) // 按分类名称筛选
                    .AndIF(!string.IsNullOrWhiteSpace(cInvStd), (x,  z) => x.cInvStd.Contains(cInvStd)) // 按标准筛选
                    .And((x,  z) => x.cInvCCode.Substring(0, 2) == "01" || x.cInvCCode.Substring(0, 2) == "02"); // 按分类代码筛选

                // 按厚度筛选
                if (thickness.HasValue)
                {
                    int formattedThickness =(int) Math.Round(thickness.Value, 1) * 10;
                    string cthick = "0000" + (formattedThickness).ToString();
                    string resultthick = cthick.Substring(cthick.Length - 4);
                    exp.And((x,  z) =>
                        !string.IsNullOrWhiteSpace(x.cInvCode) &&
                        x.cInvCode.Length >= 16 &&
                        x.cInvCode.Substring(6, 4) == resultthick);
                }

                // 按宽度筛选
                if (width.HasValue)
                {
                    int formattedWidth =(int)(Math.Round(width.Value, 1)*10);
                    string cwidth = "000000" + (formattedWidth ).ToString();
                    string resultwidth = cwidth.Substring(cwidth.Length - 6);
                    exp.And((x,  z) =>
                        !string.IsNullOrWhiteSpace(x.cInvCode) &&
                        x.cInvCode.Length >= 16 &&
                        x.cInvCode.Substring(10, 6) == resultwidth);
                }

                // 生成表达式
                var whereExpression = exp.ToExpression(); // 直接调用 ToExpression()，不需要参数

                var list1 = SqlsugarHelper.Instance.Queryable<Inventory>() // 主表用当前db就行了
                    .LeftJoin<InventoryClass>((x,  z) => x.cInvCCode.Substring(0, 6) == z.cInvCCode)
                    .Where(whereExpression) // 传递正确的表达式
                    .Select((x,  z) => new WDFT_InventoryQuery_Res()
                    {
                        cInvCode = x.cInvCode,
                        cInvName = x.cInvName,
                        cInvStd = x.cInvStd,
                        cInvCCode = x.cInvCCode,
                        cInvCName = z.cInvCName,
                    }).ToList();

                if (list1 != null && list1.Count > 0)
                {
                    return DBService.ReOKObject(list1);
                }
                else
                {
                    return DBService.ReErrObject("查询不到列表");
                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        public RetModel2 WDFT_GetRKH(WDFT_Rd01Query model)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {



                    var query = db.Queryable<RdRecord01>()//主表用当前db就行了
                                     .InnerJoin<RdRecords01>((x, y) => x.ID == y.ID)
                                      .InnerJoin<PO_Podetails>((x, y, pos) => y.iPOsID == pos.ID)
                                       .LeftJoin<PU_AppVouchs>((x, y, pos, apps) => pos.iAppIds == apps.AutoID)
                                         .LeftJoin<PU_AppVouch>((x, y, pos, apps, app) => apps.ID == app.ID);
                    if (!string.IsNullOrWhiteSpace(DbHelper.GetDbString(model.dBDate)))
                    {
                        query.Where((x, y, pos, apps, app) => x.dDate >= model.dBDate);
                    }
                    if (!string.IsNullOrWhiteSpace(DbHelper.GetDbString(model.dEDate)))
                    {
                        query.Where((x, y, pos, apps, app) => x.dDate <= model.dEDate);
                    }
                    if (!string.IsNullOrWhiteSpace(model.cInvCode))
                    {
                        query.Where((x, y, pos, apps, app) => y.cInvCode == model.cInvCode);
                    }
                    if (!string.IsNullOrWhiteSpace(model.cFree6))
                    {
                        query.Where((x, y, pos, apps, app) => y.cFree6 == model.cFree6);
                    }
                    if (!string.IsNullOrWhiteSpace(model.cReqCode))
                    {
                        query.Where((x, y, pos, apps, app) => app.cCode == model.cReqCode);
                    }

                    List<WDFT_Rd01Result> list1 = query.Select((x, y, pos, apps, app) => new WDFT_Rd01Result()
                    {
                        cCode = x.cCode,
                        dDate = x.dDate.ToString("yyyy-MM-dd"),

                        cInvCode = y.cInvCode,
                        cFree6 = y.cFree6,
                        iQuantity = (decimal)y.iQuantity,
                        bid = y.cDefine33,
                        cReqCode = app.cCode,
                        cBatch = y.cBatch,
                        cLotNo = y.cDefine28,
                        cHeatNo = y.cDefine29
                    }).ToList();


                    if (list1.Count > 0)
                    {
                        return DBService.ReOKObject(list1);
                    }
                    else
                    {
                        return DBService.ReErrObject("查询不到列表");
                    }

                }
            }
            catch (Exception ex)
            {
                //             string SQL = string.Format(@"update  formmain_0175  set  field0026 ='{1}' where field0003='{0}'
                //", shouKuan.cCode,ex.Message);
                //                DbHelper2.ExecuteNonQuery(SQL, CanShu.conStrOA);
                return DBService.ReErrObject(ex.Message);
            }
        }


        public RetModel2 WDFT_GetRKHInv(WDFT_RKHInv model)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {

                    List<WDFT_RKHInv> query = db.Queryable<CurrentStock>()//主表用当前db就行了
                  .Where((x) => x.cBatch == model.cBatch &&x.iQuantity>0 )
                .Select((x) => new WDFT_RKHInv()
                {

                    cInvCode = x.cInvCode,
                    cFree6 = x.cFree6,
                    iQuantity = (decimal)(x.iQuantity+x.fInQuantity-x.fOutQuantity),
                    iNum = (decimal)(x.iNum + x.fInNum - x.fOutNum),
                    cBatch = x.cBatch

                }).ToList();

                    foreach(var item in query)
                    {
                        if (item.iNum!=0)
                        {
                            item.iChangeRate=Math.Round( item.iQuantity/item.iNum,2);
                        }
                    }    

                   // WDFT_RKHInv query = db.Queryable<RdRecord01>()//主表用当前db就行了
                   //                  .InnerJoin<RdRecords01>((x, y) => x.ID == y.ID) 
                   //  .Where((x, y) => y.cBatch == model.cBatch)
                   //.Select((x, y) => new WDFT_RKHInv()
                   // {
                       
                   //     cInvCode = y.cInvCode,
                   //     iQuantity = (decimal)y.iQuantity, 
                   //     cBatch = y.cBatch,
                      
                   // }).First();


                    if (query !=null && query.Count>0)
                    {
                        return DBService.ReOKObject(query);
                    }
                    else
                    {
                        return DBService.ReErrObject("查询不到此入库号");
                    }

                }
            }
            catch (Exception ex)
            {
                //             string SQL = string.Format(@"update  formmain_0175  set  field0026 ='{1}' where field0003='{0}'
                //", shouKuan.cCode,ex.Message);
                //                DbHelper2.ExecuteNonQuery(SQL, CanShu.conStrOA);
                return DBService.ReErrObject(ex.Message);
            }
        }
    }
}
